// pages/safetysenceHistory/safetysenceHistory.js
const app = getApp()
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    address: "",
    type: "",
    time: "",
    reporter: "",
    content: "",
    files: [],
    dealContent: "",
    dealFiles: [],
    dealUser: "",
    hide: "",
    loading: 1,
    hasPhone: true,

    
    buttonused: false,
    dealButton: false,
    modalName: null,
    evalRes: 0, //默认没评价
    couldEval: false, // 是不是自己提交的隐患
    isChargeMan: 0, //判断是否 是当前隐患类型负责人
    //buttonTitle: '推送提醒',
    buttonTitle: '提醒负责人',
    level: ["/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
    ],
    tempUser: [],
    //由gaolin添加
    reporterWeChatId: "",
    reporterObject:{
      res: "",
      msg: ""
    },
    accounts: [],
    accountIndex: -1,
    video:"",
    videoSrc:"",
    dealVideo:"",
    dealVideoSrc:"",
    isSupervsor: false,
    superviseSchoolId: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log("history页面的==========================", options)
    if (app.globalData.departmentType == "教育局" || app.globalData.departmentType == "区教育局") {
      this.setData({
        isSupervsor: true,
        isSupervising: app.globalData.isSupervising,
        isSuddenSupervising: app.globalData.isSuddenSupervising
      })
    }
    //判断是否 是自己提交的隐患
    if (options.evaluate == 1) {
      this.setData({
        couldEval: true
      })
    }

    if (["-1", "-2"].indexOf(app.globalData.identityId) > -1) {
      this.setData({
        hasPhone: false
      })
    }


    
    // 获取隐患上报信息
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getSafetySceneById',
      method: 'POST',
      data: {
        id: parseInt(options.id)
      },
      dataType: 'json',
      success: res => {
        let photo = []
        if (res.data.photo == "" || res.data.photo == null) {
          photo.push("/images/nophoto.png")
        } else if (res.data.photo.split(',')) {
          for (let i = 0; i < res.data.photo.split(',').length; i++) {
            photo.push(app.imageUrl + res.data.photo.split(',')[i])
          }
        } else {
          photo.push(app.imageUrl + res.data.photo)
        }

        // 若为已处理，获取已处理信息 
        if (res.data.status == 5) {
          that.setData({
            hide: 'block'
          })
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getSafetySceneDeal',
            method: 'POST',
            data: {
              id: parseInt(options.id)
            },
            dataType: 'json',
            success: res => {
              let dealphoto = []
              if (res.data.dealPhoto == "" || res.data.dealPhoto == null) {
                dealphoto.push("/images/nophoto.png")
              } else if (res.data.dealPhoto.split(',')) {
                for (let i = 0; i < res.data.dealPhoto.split(',').length; i++) {
                  dealphoto.push(app.imageUrl + res.data.dealPhoto.split(',')[i])
                }
              } else {
                dealphoto.push(app.imageUrl + res.data.dealPhoto)
              }
              that.setData({
                dealPhone: res.data.phone,
                dealContent: res.data.dealContent,
                dealFiles: dealphoto,
                dealVideo: res.data.dealVideo,
                dealVideoSrc: app.imageUrl+res.data.dealVideo,
                dealUser: res.data.strDealUser,
                evalRes: res.data.evaluate ? res.data.evaluate : 0
              })
            },
            fail: res => {
              wx.showToast({
                title: '网络异常！',
                image: '/images/warning.png'
              })
            },
            complete: () => {
              that.setData({
                loading: 0
              })
            }
          })
        } else {
          that.setData({
            hide: 'none'
          })
        }
        that.setData({
          status: res.data.status,
          id: res.data.id,
          categoryId: res.data.categoryId,
          address: res.data.address,
          type: res.data.categoryName,
          time: res.data.createTime,
          dealTime: res.data.modifyTime,
          reporter: res.data.reportName,
          content: res.data.content,
          files: photo,
          video: res.data.video,
          videoSrc: app.imageUrl+res.data.video,
          reportPhone: res.data.phone,
          realname: app.globalData.realname,
          superviseSchoolId: res.data.schoolId
        })
      },
      fail: res => {
        wx.showToast({
          title: '请重试',
          image: '/images/warning.png'
        })
      },
      complete: () => {
        // 处理中 直接显示
        if (that.data.status == 7) {
          console.log("that.data.status================7")
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getWeChatPushUser',
            method: 'POST',
            data: {
              schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              console.log("getWeChatPushUser========================", res)
              that.setData({
                userList: res.data
              })
            }
          })
          that.setData({
            loading: 0
          })
        } else if (that.data.status == 6) {

          console.log("that.data.status == 6==============================")

          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getWeChatPushUser',
            method: 'POST',
            data: {
              schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              console.log("getWeChatPushUser========================", res)
              that.setData({
                userList: res.data
              })
            },
            complete: () => {
              that.setData({
                loading: 0
              })
            }
          })
          // 待处理 判断是否 是隐患负责人
          // wx.request({
          //   url: app.inspectUrl + '/weChatSystem/isCategoryChargeMan',
          //   method: 'POST',
          //   data: {
          //     categoryId: that.data.categoryId,
          //     schoolId: app.globalData.departmentId,
          //     userId: app.globalData.userId
          //   },
          //   dataType: 'text',
          //   success: res => {
          //     if (res.data == "success") {
          //       that.setData({
          //         isChargeMan: true
          //       })
          //       // wx.request({
          //       //   url: app.inspectUrl + '/weChatSystem/getWeChatPushUser',
          //       //   method: 'POST',
          //       //   data: {
          //       //     schoolId: app.globalData.departmentId
          //       //   },
          //       //   dataType: 'json',
          //       //   success: res => {
          //       //     console.log("getWeChatPushUser========================", res)
          //       //     that.setData({
          //       //       userList: res.data
          //       //     })
          //       //   }
          //       // })
          //     }
          //   },
          //   complete: () => {
          //     that.setData({
          //       loading: 0
          //     })
          //   }
          // })
        }



      }
    })
  },


  previewImage: function (e) {
    if (this.data.files[0] != "/images/nophoto.png") {
      wx.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.files // 需要预览的图片http链接列表
      })
    }
  },

  previewImageDeal: function (e) {
    if (this.data.dealFiles[0] != "/images/nophoto.png") {
      wx.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.dealFiles // 需要预览的图片http链接列表
      })
    }
  },

  phoneCall: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.dealPhone
    })
  },
  phoneCallReport: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.reportPhone
    })
  },

  clickLevel: function (e) {
    console.log(e)
    let clickId = parseInt(e.target.id)
    let tempLevel = []
    let tempLevelFont
    for (let i = 0; i < 5; i++) {
      if (i <= clickId) {
        tempLevel.push("/images/star_fill.png")
      } else {
        tempLevel.push("/images/star.png")
      }
    }
    this.setData({
      level: tempLevel,
      rank: clickId + 1
    })
  },

  evaluate: function () {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否提交评价',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')

          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/updateEvaluate',
            method: 'POST',
            dataType: 'text',
            data: {
              id: that.data.id,
              evaluate: that.data.rank
            },
            success: res => {
              console.log(res)
              if (res.data == "success") {
                wx.showToast({
                  title: "评价成功"
                })
                that.setData({
                  evalRes: that.data.rank
                })
              } else {
                wx.showToast({
                  title: "评价失败",
                  image: "/images/error.png"
                })
              }
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },

  toDeal: function () {
    let that = this

    // 隐患改变成处理中
    wx.showModal({
      title: '提示',
      content: '确认当前隐患正在被处理中？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        
           //根据上报人姓名获取绑定微信id
           wx.request({
            url:  app.inspectUrl + '/WeChat/weChatSystem/getWeChatIdByReporterName',
            method: 'GET',
            dataType:'json',
            data: {
              reporterName: that.data.reporter,
              schoolId: app.globalData.departmentId
            },
            success: res => {
              if(res.data.res == 'success'){
                let reporterWeChatId = res.data.msg
                that.setData({
                  reporterWeChatId: reporterWeChatId,
                  reporterObject:{
                    res: res.data.res,
                    msg: res.data.msg
                  }
                })
  
                console.log("reporterWeChatId=============", that.data.reporterWeChatId)
                console.log("reporterObject=============", that.data.reporterObject)
              }
            }
          })
          
        
          // 推送
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
            method: 'GET',
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token
              wx.request({
                url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                method: 'POST',
                data: {
                  categoryId: that.data.categoryId,
                  schoolId: app.globalData.departmentId
                },
                dataType: 'json',
                success: res => {
                  let unbind = []

                  console.log("res.data", res.data)
                  console.log(" res.data.length ", res.data.length)
                  for(let j=0; j<res.data.length; j++){
                    if(JSON.stringify(res.data).indexOf(JSON.stringify(that.data.reporterObject)) == -1){
                      res.data.push(that.data.reporterObject)
                      console.log("进入不相等")
                    }else{
                      console.log("进入相等")
                      break;
                    }
                  }
                  

                
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "success") {
                      
                      let datetime = util.formatTime(new Date())
                      wx.request({
                        url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                        data: {
                          template: 1,
                          accessToken: access_token,
                          touser: res.data[i].msg,
                          safetySceneId: that.data.id,
                          miniprogram: {
                            appid: 'wxfb5354f928ccc68e',
                            pagepath: 'pages/indexBlank/indexBlank'
                            },
                          data: {
                            first: {
                              value: `安全隐患由${app.globalData.realname}正在处理`
                            },
                            keyword1: {
                              value: that.data.reporter
                            },
                            keyword2: {
                              value: that.data.time
                            },
                            keyword3: {
                              value: `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                            }
                          }
                        },
                        method: 'POST',
                        dataType: 'json',
                        complete: () => {
                          that.setData({
                            buttonused: true,
                            buttonTitle: '已提醒',
                          })
                        }
                      });
                    } else {
                      //获取所有未绑定主管姓名
                      
                      unbind.push(res.data[i].msg)
                      
                    }
                  }
                  //提示未绑定信息
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    wx.showModal({
                      title: "提示",
                      showCancel: false,
                      content: msg,
                    })
                  }
                }
              })
            }
          })
        
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/updateSafetySceneStatus',
            method: 'POST',
            data: {
              safetySceneId: that.data.id,
            },
            dataType: 'text',
            success: res => {
              console.log(res)
              if (res.data == "success") {
                wx.showToast({
                  title: "变更成功"
                })
                //变成处理中
                that.setData({
                  status: 7
                })

                //变更安全隐患页状态
                let pages = getCurrentPages(); //当前页面
                let prevPage = pages[pages.length - 2]; //上一页面
                prevPage.setData({ //直接给上移页面赋值
                  loadDealing: 1
                });
              } else {
                wx.showToast({
                  title: "变更失败，请重试",
                  image: "/images/error.png"
                })
              }

            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  showModal: function () {

    console.log("消息转发=============================")
    this.setData({
      modalName: 'RadioModal'
    })
  },

  hideModal(e) {
    console.log("====")
    this.setData({
      modalName: null
    })
  },

  //新增
checkboxChange: function(e){
   console.log(e)
    let userList = []
    let userWechatId = []
    for(var i=0; i < e.detail.value.length; i++){
     userWechatId[i] = e.detail.value[i]
    }
    this.setData({
      tempUser: userWechatId
    })
},

onConfirm: function(e){
  console.log("tempuer",this.data.tempUser)
  let that = this
  wx.showModal({
    title: '提示',
    content: `确认将隐患上报处理？`,
    success(res) {
      if (res.confirm) {
        console.log('用户点击确定')
        // 推送
        wx.request({
          url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
          method: 'GET',
          dataType: 'json',
          success: res => {
            let access_token = res.data.access_token,
              datetime = util.formatTime(new Date())
            for(let i=0; i<that.data.tempUser.length; i++){
              wx.request({
                url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                data: {
                  template: 1,
                  accessToken: access_token,
                  //touser: wechatId,
                  touser: that.data.tempUser[i],
                  safetySceneId: that.data.id,
                  miniprogram: {
                    appid: 'wxfb5354f928ccc68e',
                    pagepath: 'pages/indexBlank/indexBlank'
                    },
                  data: {
                    first: {
                      value: `安全隐患由${app.globalData.realname}转发给您`
                    },
                    keyword1: {
                      value: that.data.reporter
                    },
                    keyword2: {
                      value: that.data.time
                    },
                    keyword3: {
                      value:  `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                    }
                  }
                },
                method: 'POST',
                dataType: 'json',
                success: res => {
                  wx.showToast({
                    title: "推送成功"
                  })
                  that.setData({
                    dealButton: true,
                    modalName: null
                  })
                },
                complete: () => {
                
                }
              })
            }
          }
        });
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })

},


  // toOther: function (e) {
  //   console.log("用户上交",e)
  //   let that = this,
  //      wechatId = e.currentTarget.dataset.wechatid,
  //     forwordName = e.currentTarget.dataset.name

  //   // 上报给他人处理
  //   wx.showModal({
  //     title: '提示',
  //     content: `确认将隐患上报给${forwordName}处理？`,
  //     success(res) {
  //       if (res.confirm) {
  //         console.log('用户点击确定')
  //         // 推送
  //         wx.request({
  //           url: app.inspectUrl + '/weChatSystem/getAccessTokenForSendMsg',
  //           method: 'GET',
  //           dataType: 'json',
  //           success: res => {
  //             let access_token = res.data.access_token,
  //               datetime = util.formatTime(new Date())
  //             wx.request({
  //               url: app.inspectUrl + '/weChatSystem/sendMessage',
  //               data: {
  //                 template: 1,
  //                 accessToken: access_token,
  //                 touser: wechatId,
  //                 // touser: "oq0rl1H9-ClV3vUpUubtUQmE12wA",
  //                 safetySceneId: that.data.id,
  //                 data: {
  //                   first: {
  //                     value: "【安全现场隐患】"
  //                   },
  //                   keyword1: {
  //                     value: app.globalData.realname
  //                   },
  //                   keyword2: {
  //                     value: datetime
  //                   },
  //                   keyword3: {
  //                     value: `${that.data.reporter}在${that.data.time}发现的${that.data.type}类型隐患需由您处理`
  //                   }
  //                 }
  //               },
  //               method: 'POST',
  //               dataType: 'json',
  //               success: res => {
  //                 wx.showToast({
  //                   title: "推送成功"
  //                 })
  //                 that.setData({
  //                   dealButton: true,
  //                   modalName: null
  //                 })
  //               },
  //               complete: () => {
                
  //               }
  //             })

  //           }
  //         });
  //       } else if (res.cancel) {
  //         console.log('用户点击取消')
  //       }
  //     }
  //   })

  // },

  //提醒负责人
  remind: function (e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确认再次提醒处理安全隐患？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          // 推送
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
            method: 'GET',
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token
              wx.request({
                url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                method: 'POST',
                data: {
                  categoryId: that.data.categoryId,
                  schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
                },
                dataType: 'json',
                success: res => {
                  let unbind = []
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "success") {
                      let datetime = util.formatTime(new Date())
                      wx.request({
                        url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                        data: {
                          template: 1,
                          accessToken: access_token,
                          touser: res.data[i].msg,
                          safetySceneId: that.data.id,
                          miniprogram: {
                            appid: 'wxfb5354f928ccc68e',
                            pagepath: 'pages/indexBlank/indexBlank'
                          },
                          data: {
                            first: {
                              value: "发现安全隐患，请及时处理"
                            },
                            keyword1: {
                              value: that.data.reporter
                            },
                            keyword2: {
                              value: that.data.time
                            },
                            keyword3: {
                              value:  `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                            }
                          }
                        },
                        method: 'POST',
                        dataType: 'json',
                        
                        complete: () => {
                          that.setData({
                            buttonused: true,
                            buttonTitle: '已提醒',
                          })
                        }
                      });
                    } else {
                      //获取所有未绑定主管姓名
                      unbind.push(res.data[i].msg)
                    }
                  }
                  //提示未绑定信息
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    wx.showModal({
                      title: "提示",
                      showCancel: false,
                      content: msg,
                    })
                  }
                }
              })
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

})